<template>
	<RequireLoginVue>
		<view class="container">
			
			<!-- 盘点单头 -->
			<view class="header">
				<picker
				mode="selector"
				:range="workAreaGroup"
				range-key="workingAreaName"
				:value="index"
				@change="handleChange"
				>
					<view class="workArea">
						盘点区域:{{workAreaGroup[index]?.workingAreaName ||'请选择'}}
					</view>
				</picker>
				<br>
				<view class="date">
					<text>
						盘点日期:
					</text>
					<uni-datetime-picker
					position="top"
					cursor-spacing="70"
					:adjust-position="false"
					v-model="date"
					type="date"
					:start="start"
					:end="end"
					/>
				</view>
				
			</view>
			
			<!-- 获取明细 -->
			<view class="">
				
				<!-- <input type="text" v-model="goodsCode" @confirm="findGoods" confirm-type="done"/> -->
				<input
					v-model="goodsCode"
					placeholder="请输入物料编号"
					class="search-input"
					@confirm="findGoods"
				/>
				<view class="btn">
					<button @tap="startScan"  class="search-btn">扫码</button>
					<button  @tap="save">保存</button>
					<button  @tap="check">审核</button>
					<button  @tap="findGoods">查询</button>
				</view>
			</view>
			
			<!-- 弹出框 -->
			<view v-if="visible" class="modal-mask">
				<view class="tck">
					<!-- 明细 -->
					<view>
						物料编号:{{checkDetail.goodsCode}}
						<br>
						物料名称:{{checkDetail.goodsName}}
						<br>
						图号-版本/规格:{{checkDetail.designNumberVerSpec}}
						<br>
						库位:{{checkDetail.waLocationCode}}
						<br>
						<view class="input">
							初盘数:<input placeholder="请输入初盘数" v-model="recheckQty"/>
						</view>
						<br>
						<view class="input">
							复盘数:<input placeholder="请输入复盘数" v-model="recheckQty2"/>
						</view>
					</view>
					<!-- 按钮 -->
					<view class="btn">
						<button @tap="exit">退出</button>
						<button @tap="addDetail">确认</button>
					</view>
					
				</view>
			</view>
			
			<text v-if="billNo!=null">盘点单编号:{{billNo}}</text>
			<!-- 盘点单明细 -->
			<view v-for="check in checkDetailGroup" :key="check.id" class="card">
			<text>1.物料编号:{{check.goodsCode}}</text>
			<br>
			<text>2.物料名称:{{check.goodsName}}</text>
			<br>
			<text>3.规格-版本/图号:{{check.designNumberVerSpec}}</text>
			<br>
			<text>4.盘点数量:{{check.recheckQty}}</text>
			<br>
			<text>5.库位:{{check.waLocationCode}}</text>
			</view>
			
			<!-- <view class="fixed-bottom"> -->
				
				
				
			<!-- </view> -->
			
		</view>
	</RequireLoginVue>
</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue';
import {onLoad} from '@dcloudio/uni-app'
import { DOWNLOAD_BASE, LAN_URL } from '../config/global';
import {CheckDetail} from '../models/CheckDetail';
import {CheckDetailGroup} from '../models/CheckDetailGroup';
import { WorkArea } from '../models/WorkArea';
import { WorkAreaGroup } from '../models/WorkAreaGroup';
import RequireLoginVue from '../components/RequireLogin.vue';

	//常量配置
	const ADD_URL = '/api/checkDetail/add'//添加盘点单
	const FINDWORKAREA_URL = '/api/workArea/findByProperty'//查询所有仓库
	const FINDGOODS ='/api/checkDetail/findByGoodsCode'//根据物料编号查询对应的物料
	const GETBILLNO = '/api/checkDetail/getBillNo'//获取盘点单号
	const CHECK = '/api/checkDetail/check'//进行审核
	
	//响应式状态
	const userID = ref<string | null>(null)
	const userName = ref<string | null>(null)
	const checkDetail = ref()//每次添加的明细
	const checkDetailGroup = ref([])//每次明细添加完存放的数组
	const workArea = ref<WorkArea>()//你所选择的仓库
	const workAreaGroup = ref([])//可选择的仓库数组
	const index=ref(-1)
	const date = ref('')//所选的日期
	const start = ref('2000-01-01')//日期选择的范围（开始）
	const end = ref('3000-01-01')//日期选择的范围（结束）
	const goodsCode = ref('')//文本框放置的物料编号
	const visible=ref(false)//负责弹出框的开关
	const recheckQty = ref('')//初盘数
	const recheckQty2 = ref('')//复盘数
	const x = ref(false);//用于判断是否要停止
	const billNo=ref(null)//用于存放返回的bill_no
	
	//初始化
	onMounted(()=>{
		findAllWorkArea()
		date.value=getToday()
	})
	
	//获取所有仓库
	const findAllWorkArea = async () =>{
		const {data} = await uni.request({
			url:`${LAN_URL}${FINDWORKAREA_URL}`,
			method:'POST',
			data:{property:'仓库'}
		})
		data.forEach(item=>{
			
			const workArea = mapToWorkArea(item)
			workAreaGroup.value.push(workArea)
			
		})
	}
	
	//数据转换
	const mapToWorkArea = (data:any) : WorkArea =>({
		workingAreaCode:data.workingAreaCode,
		workingAreaName:data.workingAreaName,
		property:data.property
	})
	
	//选择变化事件处理(仓库)
	const handleChange = (e)=>{
		const y = ref(false)//判断数组是否有值
		console.log(checkDetailGroup)
		checkDetailGroup.value.forEach(item=>{
			if(item!=null)y.value=true;
		})
		if(y.value){return}//当有明细时不得修改仓库
		
		index.value = e.detail.value
		
		workArea.value=workAreaGroup.value[index.value]
		
		console.log(workArea.value)
		
	}
	
	//获取当前日期
	const getToday=()=>{
		const d = new Date()
		const year = d.getFullYear()
		const month = String(d.getMonth()+1).padStart(2,'0')
		const day = String(d.getDate()).padStart(2,'0')
		return `${year}-${month}-${day}`
	}
	
	//判断是否是纯数字
	const isNumber=(str)=>{
		return /^-?\d+(\.\d+)?$/.test(str);
	}
	
	//确认明细
	const addDetail = ()=>{
		if(!isNumber(recheckQty.value) || !isNumber(recheckQty2.value)){
			uni.showToast({
				title:'请规范输入初盘数和复盘数',
				icon:'none'
			})
			return;
		}
		
		if(Number(recheckQty.value)<0 || Number(recheckQty2.value)<0){
			uni.showToast({
				title:'初盘数和复盘数需大于0',
				icon:'none'
			})
			return;
		}
		
		
		checkDetail.value.recheckQty=Number(recheckQty2.value)
		console.log(checkDetail.value)
		checkDetailGroup.value.push(checkDetail.value)
		visible.value=false
		recheckQty.value='0'
		recheckQty2.value='0'
	}
	
	/* 扫码 */
	const startScan = async () => {
	  try {
	    const res = uni.scanCode({
			scanType: ['qrCode', 'barCode'],
			onlyFromCamera: true,
			success: (result) => {
				handleScanResult(result)
			},
			fail: (err) => {
				handleScanError(err)
			}
		})
	  } catch (error) {
	    handleScanError(error)
	  }
	}
	
	/* 扫码结果处理 */
	const handleScanResult = (result: UniApp.ScanCodeSuccessRes) => {
		goodsCode.value = result.result
		console.log("scanResult:", goodsCode.value)
		console.log("resule:", result.result)
		if (result.scanType === 'EAN_13') {
			console.log("1")
		}
		findGoods();
	}
	
	/* 扫码错误 */
	const handleScanError = (error: any) => {
		console.error('扫码失败:', error)
		uni.showToast({
			title: '扫码失败，请重试',
			icon: 'none'
	  })
	}
	
	//查询物料
	const findGoods = async ()=>{
		
		
		
		//如果数组已有该物料，则停止
		if(checkDetailGroup.value!=null){
			checkDetailGroup.value.forEach(item=>{
				if(item.goodsCode==goodsCode.value){
					uni.showToast({
						title:'已有该物料',
						icon:'none'
					})
					x.value=true;
				}
			})
		}
		if(x.value==true){return}
		

		
		console.log(goodsCode.value)
		if (!goodsCode.value || !goodsCode.value.trim()) {
			uni.showToast({ title: '请输入物料编号', icon: 'none' })
			return;
		}
		
		if(workArea.value==null){
			uni.showToast({
				title:'请选择盘点区域',
				icon:'none'
			})
			return;
		}
		
		if(date==null){
			uni.showToast({
				title:'请选择盘点日期',
				icon:'none'
			})
			return;
		}
				
		console.log("发送请求")
		console.log("workArea : "+workArea.value)
		const {data} = await uni.request({
			url:`${LAN_URL}${FINDGOODS}`,
			method:'POST',
			data:{
				goodsCode:goodsCode.value,
				workingAreaCode:workArea.value.workingAreaCode
			}
		})
		
		//查询结果为空
		if(data==null || data==''){
			uni.showToast({
				title:'盘点区域内无该物料',
				icon:'none'
			})
			return;
		}
		
		data.forEach(item=>{
			checkDetail.value = mapToCheckDetail(item)
			
			visible.value=true
			console.log(data)
			console.log(checkDetail.value)
			console.log(checkDetailGroup.value)
		})
		
	}
	
	// 数据转换
	const mapToCheckDetail = (data: any) : CheckDetail => ({
		id:data.id,
		billNo:data.billNo,
		showNo:data.showNo,
		goodsCode:data.goodsCode,
		imageUrl:data.imageUrl ? `${DOWNLOAD_BASE}${data.imageUrl}` : undefined,
		pdfUrl:data.pdfUrl ? `${DOWNLOAD_BASE}${data.pdfUrl}` : undefined,
		goodsName:data.goodsName,
		onHandQty:data.onHandQty,
		designNumberVerSpec:data.designNumberVerSpec,
		unitCode:data.unitCode,
		nowQty:data.nowQty,
		price:data.price,
		recheckQty:data.recheckQty,
		recheckPrice:data.recheckPrice,
		recheckAmount:data.recheckAmount,
		checkDiffCode:data.checkDiffCode,
		remark:data.remark,
		productCode:data.productCode,
		waLocationCode:data.waLocationCode
	})
	
	//取消添加
	const exit = ()=>{
		checkDetail.value=null//清空添加的明细
		visible.value=false//关闭弹出框
		recheckQty.value='0'
		recheckQty2.value='0'
	}
	
	//保存盘点单
	const save = async () =>{
		
		if(checkDetailGroup.value==null || checkDetailGroup.value==""){
			uni.showToast({
				title:"无盘点明细",
				icon:'none'
			})
			return;
			}
		if(workArea.value==null){
			uni.showToast({
				title:"无盘点区域",
				icon:'none'
			})
			return;
			}
		if(date.value==null){
			uni.showToast({
				title:"无盘点日期",
				icon:'none'
			})
			return;
		    }
			const userData = uni.getStorageSync("user")
			userID.value=userData.id
			userName.value=userData.name
		console.log(userData.name)
		
		const {data} = await uni.request({
			url:`${LAN_URL}${ADD_URL}`,
			method:'POST',
			data:{
				workingAreaCode:workArea.value.workingAreaCode,//盘点区域
				PDdate:date.value,//盘点日期
				checkDetails:checkDetailGroup.value,//盘点明细
				userName:userData.name//用户名称
			}
		})
		console.log(data.status)
		if(data.status=='1'){
			uni.showToast({
				title:"添加成功",
				icon:'success'
			})
			billNo.value=data.billNo
		}
		if(data.status=='0'){
			uni.showToast({
				title:"添加失败",
				icon:'error'
			})
		}
	}
	
	//审核
	const check = async () =>{
		if(billNo.value==null){
			uni.showToast({
				title:'请保存后审核',
				icon:'none'
			})
			return
		}
		
		const {data} = await uni.request({
			url:`${LAN_URL}${CHECK}`,
			method:'POST',
			data:{
				billNo:billNo.value,
				userName:userName.value,
				userID:userID.value
			}
		})
		console.log(data)
		if(data.status==0){
			uni.showToast({
				title:data.content,
				icon:'error'
			})
			return
		}
		uni.showToast({
			title:data.content,
			icon:'success'
		})
	}
	
</script>

<style lang="scss" scoped>
	.header{
		border: 1rpx solid black;
		padding: 2rpx;
	}
	.date{
		display: flex;
		z-index: 2000;
	}
	.btn{
		display: flex;
		gap: 20rpx;
		margin: 30rpx 0;
			
		button {
			flex: 1;
			height: 80rpx;
			border-radius: 40rpx;
			background: #3498db;
			color:white;
			
			&:active {
				background: #e0e0e0;
			}
		}
	}
	.modal-mask {
	  position: fixed;
	  top: 0;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  background: rgba(0,0,0,0.5);
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  z-index: 999;
	  .tck{
		  background-color: white;
		  border: 1px solid black;
		  border-radius: 40rpx;
		  padding: 10rpx;
	  }
	}
	.search-input {
		flex: 1;
		height: 100rpx;
		padding: 0 30rpx;
		border: 1rpx solid #ddd;
		border-radius: 40rpx;
	}
	.input{
		display: flex;
		input{
			background-color: white;
			border: 1px solid black;
			
		}
	}
	
	.card {
	  margin: 15rpx 0;
	    padding: 20rpx;
	    border: 1rpx solid #e74c3c; /* 外边框 */
	    border-left: 5rpx solid #3498db; /* 左侧强调色条 */
	    background: #fff;
	}
	/* 固定在底部的样式 */
	.fixed-bottom {
	  position: fixed; /* 固定定位 */
	  bottom: 0; /* 距离底部0 */
	  left: 0;
	  width: 100%; /* 宽度占满屏幕 */
	  height: 70px; /* 高度自定义 */
	  background-color: white; /* 背景色 */
	  border: 1px solid black;
	  display: flex;
	  justify-content: center;
	  align-items: center;
	  // color: #fff; /* 文字颜色 */
	  z-index: 1000; /* 层级高于内容 */
	}

</style>
